"""
MySQL与Elasticsearch实时同步模块
主要用于初始化MySQL到ES的同步机制
"""
from .es_utils.mysql_es_sync import MySQLESSync
import logging
import threading

# 配置日志
logger = logging.getLogger('elasticsearch')

# 创建全局同步实例
sync_instance = MySQLESSync()

# 同步控制锁
sync_lock = threading.Lock()
sync_running = False
sync_thread = None

def start_sync_process():
    """启动MySQL到ES的同步进程"""
    global sync_running, sync_thread
    
    with sync_lock:
        if sync_running:
            logger.info("同步进程已经在运行中")
            return False, "同步进程已经在运行中"
        
        # 连接ES
        if not sync_instance.connect_es():
            return False, "无法连接到Elasticsearch服务器"
            
        # 连接MySQL
        if not sync_instance.connect_mysql():
            return False, "无法连接到MySQL服务器或binlog配置有误"
            
        # 标记为运行状态
        sync_running = True
        
        # 创建同步线程
        sync_thread = threading.Thread(target=sync_instance.start_sync)
        sync_thread.daemon = True
        sync_thread.start()
        
        logger.info("MySQL到ES同步进程已启动")
        return True, "同步进程已启动"

def stop_sync_process():
    """停止MySQL到ES的同步进程"""
    global sync_running, sync_thread
    
    with sync_lock:
        if not sync_running:
            logger.info("同步进程未运行")
            return False, "同步进程未运行"
            
        # 停止同步
        sync_instance.stop_sync()
        sync_running = False
        
        # 等待线程结束
        if sync_thread and sync_thread.is_alive():
            sync_thread.join(timeout=5)
            
        logger.info("MySQL到ES同步进程已停止")
        return True, "同步进程已停止"

def rebuild_es_index():
    """重建ES索引"""
    return sync_instance.rebuild_index() 